from django.db.transaction import atomic
from django.shortcuts import render

# Create your views here.
from django.utils.decorators import method_decorator
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.exceptions import ValidationError, APIException
from rest_framework.generics import ListAPIView, RetrieveAPIView, DestroyAPIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet

from api.filters import StudentFilter
from api.pages import MyNumberPagination
from api.serializers import CollegeSimpleSerializer, CollegeSerializer, ClassSerializer, ClassSimpleSerializer, \
    StudentSimpleSerializer, StudentSerializer, TeacherSerializer, LessonSerializer
from common.models import College, Student, Class, StuLesson, Teacher, Lesson


class CollegeViewSet(ListAPIView, RetrieveAPIView, GenericViewSet):
    queryset = College.objects.all()
    serializer_class = CollegeSimpleSerializer

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return CollegeSerializer
        return self.serializer_class


class ClassViewSet(ListAPIView, RetrieveAPIView, DestroyAPIView, GenericViewSet):
    queryset = Class.objects.all().order_by('clsid')
    serializer_class = ClassSimpleSerializer

    def get_serializer_class(self):
        if self.action != 'list':
            return ClassSerializer
        return self.serializer_class


class TeacherViewSet(ModelViewSet):
    queryset = Teacher.objects.all()
    serializer_class = TeacherSerializer


class LessonViewSet(ModelViewSet):
    queryset = Lesson.objects.all()
    serializer_class = LessonSerializer

    def get_queryset(self):
        queryset = self.queryset



@method_decorator(decorator=atomic(), name='perform_destroy')
class StudentViewSet(ListAPIView, RetrieveAPIView, DestroyAPIView, GenericViewSet):
    queryset = Student.objects.all().order_by('stuid')
    serializer_class = StudentSerializer
    pagination_class = MyNumberPagination
    filter_backends = (DjangoFilterBackend, )
    filterset_class = StudentFilter

    def perform_destroy(self, instance):
        stulesson = StuLesson.objects.filter(student__stuid=instance.stuid)
        cls = Class.objects.filter(clsid=instance.cls.clsid).first()
        cls.cls_num -= 1
        cls.save()
        for sl in stulesson.all():
            sl.delete()
        instance.delete()
